package com.example.exam.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.exam.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * @author zhang
 */
@Component
public class JwtUtils {
    // 从配置文件中读取密钥
    @Value("${jwt.key}")
    private String key;

    // 生成token
    public String createToken(User user) {
        Algorithm ALGORITHM_256 = Algorithm.HMAC256(key);//密钥
        return JWT.create()
                .withIssuer("auth0")
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + 60 * 60 * 1000))
                .withClaim("id", user.getId())
                .sign(ALGORITHM_256);
    }

    public String createToken(String username) {
        Algorithm ALGORITHM_256 = Algorithm.HMAC256(key);//密钥
        return JWT.create()
                .withIssuer("auth0")
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + 60 * 60 * 1000))
                .withClaim("username", username)
                .sign(ALGORITHM_256);
    }

    // 验证token
    public Boolean verifyToken(String token) {
        Algorithm ALGORITHM_256 = Algorithm.HMAC256(key);//密钥
        try {
            JWT.require(ALGORITHM_256).build().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 获取token中的id
    public String get(String token, String key) {
        Algorithm ALGORITHM_256 = Algorithm.HMAC256(key);//密钥
        return JWT.require(ALGORITHM_256).build().verify(token).getClaim(key).asString();
    }
}
